package com.tony.juc;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: AtomicLongFieldUpdaterDemo001
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/06/21:38
 * @Description: 属性类型原子操作类
 */
public class AtomicLongFieldUpdaterDemo001 {

    public static void main(String[] args) {

        /*AtomicLongFieldUpdater updater = AtomicLongFieldUpdater.newUpdater(Book002.class,"id");
        System.out.println(updater.getClass());*/

        Book002 book = new Book002(1002,"java就业编程实战",69.8);//实例化对象
        book.setId(2222);//修改属性内容
        System.out.println(book);

    }

}

class Book002 {
//    volatile long id; //图书的编号，使用long类型

    //此时的属性如果想要使用原子属性修改器，则必须使用volatile关键字定义，否则执行时会出现如下操作
    //  java.lang.IllegalArgumentException: Must be volatile type
    private volatile long id;   //图书编号
    private String title;   //无需同步的属性
    private double price;   //无需同步的属性

    public Book002(long id, String title, double price) {
        this.id = id;
        this.title = title;
        this.price = price;
    }

    //此时的id时需要进行同步处理的
    public void setId(long id) {
        AtomicLongFieldUpdater updater = AtomicLongFieldUpdater.newUpdater(Book002.class,"id");
        updater.compareAndSet(this,this.id,id);//CAS修改操作
    }

    @Override
    public String toString() {
        return "【图书】ID = " + this.id + "、名称 = " + this.title + "、价格 = " + this.price;
    }
}
